<?php
/**
 * 基本模型封装.
 * Authors Duanlang (Duanlang@iyenei.com)
 * Date: 2016/8/22
 * Time: 10:57
 */
class MY_Model extends CI_Model {
    /**
     * @var CI_DB_active_record
     */
    public $db;

    //定义数据库表
   protected $_tables = array();
   //数据库序号
   protected $db_number = '';

   protected $is_select_db = false;
    //查询条件方法
   private $_methods = array('where_in', 'or_where', 'or_where_in', 'where_not_in', 'or_where_not_in', 'having');

    /**
     * 分表操作
     * @author duanlang<duanlang@iyene.com>
     * @param  [array] $table [表数据]
     * @param  [string] $userId [用户id]
     * @return [array] [处理好的表]
     */
    public function branch_table($table = array(), $userId = 0)
    {
        $database = $this->db->database;
        $tableIndex = '';
        if ($userId > 0) {
            list($dbIndex, $tableIndex) = \common\components\CompanyDbCache::getInstance()->getCompanyDbInfoByVisitId($userId);
            if ($this->is_select_db) {
                $database .= '_' . $dbIndex;
            }
        }

        //分表处理
        $db_table = array();
        foreach($table as $temp => $val)
        {
            $db_table[$temp] = $val['table_name'];
            if($val['is_branch'] == true && $tableIndex != '')
            {
                $db_table[$temp] = $val['table_name'].'_'.$tableIndex;
            }

            $db_table[$temp] = $database . '.' . $db_table[$temp] ;
        }
        return $db_table;
    }
    /**
     * 条件参数处理
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @since ${DATE}
     * @param $options array 条件参数
     * @return void
     */
    protected function _parse_options($options = array())
    {
        if (!empty($options)) {
            foreach ($options as $key => $val) {
                if (in_array($key, $this->_methods)) {
                    foreach ($val as $k => $v) {
                        $this->db->$key($k, $v);
                    }
                } else {
                    if ($key == 'where') {
                        if (is_array($val)) {
                            foreach ($val as $vk => $vv) {
                                is_numeric($vk) ? $this->db->where($vv) : $this->db->where($vk, $vv);
                            }
                        } else {
                            $this->db->where($val);
                        }
                    } else {
                        $this->db->$key($val);
                    }
                }
            }
        }
    }
    /**
     * 获取总数
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @since ${DATE}
     * @param array $options 查询条件
     * @return mixed
     */
    public function count($options = array())
    {
        $this->_parse_options($options);
        return $this->db->count_all_results($this->_tables['default']);
    }
    /**
     * 获取所有列表内容
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @param $options 查询条件
     * @param $orderby  排序 array('id'=> 'desc') 支持多数组
     * @return mixed
     */
    public function listsAll($field, $options = array(), $orderby = array())
    {
        if(empty($options))
        {
            return false;
        }

        //处理查询条件
        $this->_parse_options($options);
        //处理排序
        if(!empty($orderby))
        {
            foreach($orderby as $ok => $ov)
            {
                $this->db->order_by($ok, $ov);
            }
        }
        $result = $this->db->select($field)->get($this->_tables['default'])->result_array();
        return $result;
    }

    /**
     * 获取列表不要总条数量
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @since ${DATE}
     * @param $limit 每页显示
     * @param $page  第几页
     * @param $options 查询条件
     * @param $orderby  排序 array('id'=> 'desc') 支持多数组
     * @return mixed
     */
    public function feach($limit = 10, $page = 1, $options = array(), $orderby = array(), $field = '*', $group_by = array())
    {
        //当前分页的位移计算
        $offset = ($page - 1) * $limit;
        $offset = $offset > 0 ? $offset : 0;
        //处理查询条件
        $this->_parse_options($options);
        //处理排序
        if(!empty($orderby))
        {
            foreach($orderby as $ok => $ov)
            {
                $this->db->order_by($ok, $ov);
            }
        }

        if(!empty($group_by))
        {
            $this->db->group_by($group_by);
        }
        //处理分页
        if ($limit > 0) {
            $this->db->limit($limit, $offset);
        }
        $result = $this->db->select($field)->get($this->_tables['default'])->result_array();
        return $result;
    }
    /**
     * 列表查询
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @since ${DATE}
     * @param $limit 每页显示
     * @param $page  第几页
     * @param $options 查询条件
     * @param $orderby  排序 array('id'=> 'desc') 支持多数组
     * @return mixed
     */
    public function lists($limit = 10, $page = 1, $options = array(), $orderby = array(),$field = '*')
    {
        //每页显示数量
        $result['limit'] = $limit;
        //当前第几页
        $result['page']  = $page;
        //当前分页的位移计算
        $offset = ($page - 1) * $limit;
        $offset = $offset > 0 ? $offset : 0;
        //获取分页总条数
        $result['count'] = $this->count($options);
        $result['total_page'] = ceil($result['count']/$limit);
        //处理查询条件
        $this->_parse_options($options);
        //处理排序
        if(!empty($orderby))
        {
            foreach($orderby as $ok => $ov)
            {
                $this->db->order_by($ok, $ov);
            }
        }
        //处理分页
        if ($limit > 0) {
            $this->db->limit($limit, $offset);
        }
        $result['data'] = $this->db
            ->select($field)
            ->get($this->_tables['default'])
            ->result_array();
        return $result;
    }
    /**
     * 获取排名
     * @author duanlang<duanlang@iyene.com>
     * @param  [type] $number [数量]
     * @param  array $orderby [排序]
     * @param  array $options [条件]
     * @return [type] [列表]
     */
    public function getRanking($number, $orderby = array(), $options = array())
    {
        if(empty($options))
        {
            return false;
        }

        //处理查询条件
        $this->_parse_options($options);
        //处理排序
        if(!empty($orderby))
        {
            foreach($orderby as $ok => $ov)
            {
                $this->db->order_by($ok, $ov);
            }
        }
        $this->db->limit($number, 0);
        return $this->db->get($this->_tables['default'])->result_array();
    }
    /**
     * 获取一个字段的值
     * @author duanlang<duanlang@iyene.com>
     * @param  [type] $field [字段名称]
     * @param  [type] $options [条件]
     * @return [type] [返回字段值]
     */
    public function getField($field, $options=array())
    {
        if(empty($options))
        {
            return false;
        }
        //处理查询条件
        $this->_parse_options($options);
        $result = $this->db->select($field)->get($this->_tables['default'])->row_array();
        return  !empty($result) ? $result[$field] : '';
    }
    /**
     * 获取单条记录
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @since ${DATE}
     * @param $options array 查询条件
     * @return mixed
     */
    public function info($options = 0 , $filed = '', $orderby = '')
    {
        if (is_numeric($options)) {
            $this->db->where('id', $options);
        } else {
            $this->_parse_options($options);
        }
        if (!empty($filed)) {
            $this->db->select($filed);
        }
        //处理排序
        if(!empty($orderby))
        {
            foreach($orderby as $ok => $ov)
            {
                $this->db->order_by($ok, $ov);
            }
        }
        $result = $this->db->get($this->_tables['default'])->row_array();
        return $result;
    }

    /**
     * 编辑一条记录
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @since ${DATE}
     * @param $info array 编辑的数据
     * @param $id 修改的主键
     * @return bool
     */
    public function edit($info, $options)
    {
        if (is_numeric($options)) {
            $this->db->where('id', $options);
        } else {
            $this->_parse_options($options);
        }
        return $this->db->update($this->_tables['default'], $info);
    }

    /**
     * 批量编辑
     * @author duanlang<duanlang@iyene.com>
     * @param  string $mytable [编辑的表名]
     * @param  [type] $data [编辑的数据 二维数据]
     * @param  [type] $field [编辑的字段键名]
     * @return [type] [description]
     */
    public function update_batch($data = NULL, $field = NULL, $table = '')
    {
        if(empty($table))
        {
            $table = $this->_tables['default'];
        }
        $this->db->update_batch($table, $data, $field);
    }
    /**
     * 每一个字段增加1
     * @author duanlang<duanlang@iyene.com>
     * @param  [type] $field [description]
     * @param  [type] $number [description]
     * @param  [type] $options [description]
     */
    public function setInc($field, $number, $options)
    {
        if (is_numeric($options)) {
            $this->db->where('id', $options);
        } else {
            $this->_parse_options($options);
        }
        $this->db->set($field, $field.'+'.$number, FALSE);
        return $this->db->update($this->_tables['default']);
    }
    /**
     * 每一个字段减少1
     * @author duanlang<duanlang@iyene.com>
     * @param  [type] $field [description]
     * @param  [type] $number [description]
     * @param  [type] $options [description]
     */
    public function setDec($field, $number, $options)
    {
        if (is_numeric($options)) {
            $this->db->where('id', $options);
        } else {
            $this->_parse_options($options);
        }
        $this->db->set($field, $field.'-'.$number, FALSE);
        return $this->db->update($this->_tables['default']);
    }
    /**
     * 编辑一条记录
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @since ${DATE}
     * @param $info array 编辑的数据
     * @param $id 修改的主键
     * @return bool
     */
    public function add($info)
    {
        return $this->db->insert($this->_tables['default'], $info) ? $this->db->insert_id() : false;
    }

    /**
     * 批量插入
     * @author duanlang<duanlang@iyene.com>
     * @param  [type] $mytable [要插入的表]
     * @param  [type] $data [要插入的数据 二维数组]
     * @return [type] [description]
     */
    public function insert_batch($data, $mytable = '')
    {
        if(empty($mytable))
        {
            $mytable = $this->_tables['default'];
        }
        return $this->db->insert_batch($mytable, $data);
    }
    /**
     *删除一条记录
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @since ${DATE}
     * @param $id int 删除的主键
     * @return bool
     */
    public function del($options)
    {
        if (is_numeric($options)) {
            $this->db->where('id', $options);
        } else {
            $this->_parse_options($options);
        }
        return $this->db->delete($this->_tables['default']);
    }

    /**
     * 逻辑删除一条记录
     * @author duanlang<duanlang@iyene.com>
     * @reviewer
     * @since ${DATE}
     * @param $id int 删除记录的id
     * @return bool
     */
    public function del_logic($options)
    {
         if (is_numeric($options)) {
            $this->db->where('id', $options);
        } else {
            $this->_parse_options($options);
        }
        return $this->db->update($this->_tables['default'], array('is_delete' => '1', 'dt_delete' =>time()));
    }

    /**更新记录
     * @param $id
     * @param $data
     * @return bool
     */
    public function update($id,$data)
    {
        $this->db->where('id', $id);
        $res=$this->db->update($this->_tables['default'], $data);
        if($res){
            return $id;
        }else{
            return false;
        }
    }

    /**
     * 替换记录信息
     *
     * @param array $data
     * @param array $options
     * @author jiaozi<jiaozi@iyenei.com>
     * @return int|bool
     */
    public function replace($data, $options)
    {
        $info = $this->info($options);
        if (empty($info)) {
            return $this->add($data);
        } else {
            $this->edit($data, [
                'where' => [
                    'id' => $info['id']
                ]
            ]);
            return $info['id'];
        }
    }
}